<?php
class ProjectRatingsController extends AppController
{
    public $name = 'ProjectRatings';
    public $components = array(
        'Email'
    );
    public $uses = array(
        'ProjectRating',
        'EmailTemplate'
    );
    public function beforeFilter()
    {
        if (!Configure::read('Project.is_enable_idea')) {
            throw new NotFoundException(__l('Invalid request'));
        }
        parent::beforeFilter();
    }
    public function index()
    {
        if (empty($this->request->params['named']['project_id'])) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $backer = $this->ProjectRating->Project->ProjectFund->find('count', array(
            'conditions' => array(
                'OR' => array(
                    array(
                        'ProjectFund.is_paid' => 1
                    ) ,
                    array(
                        'ProjectFund.is_paid' => 0
                    ) ,
                ) ,
                'ProjectFund.project_id' => $this->request->params['named']['project_id'],
                'ProjectFund.user_id' => $this->Auth->user('id') ,
                'ProjectFund.is_cancelled' => 0,
                'ProjectFund.is_refunded' => 0
            ) ,
            'recursive' => - 1
        ));
//        if ($backer || $this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            if (Configure::read('Project.is_enable_idea') || $this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            $this->pageTitle = __l('Project Votings');
            $this->ProjectRating->recursive = 1;
            $this->paginate = array(
                'conditions' => array(
                    'ProjectRating.project_id' => $this->request->params['named']['project_id']
                ) ,
                'contain' => array(
                    'User' => array(
                        'UserAvatar' => array(
                            'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.filename',
                            'UserAvatar.dir',
                            'UserAvatar.width',
                            'UserAvatar.height'
                            )
                        ) ,
                        'fields' => array(
                            'User.username'
                        )
                    ) ,
                    'Project' => array(
                        'fields' => array(
                            'Project.id',
                            'Project.name',
                            'Project.slug',
                            'Project.project_rating_count'
                        )
                    )
                )
            );
			if ($this->RequestHandler->prefers('json')) {
			$iphone_project_voters = $this->paginate();
			for($i=0;$i<count($iphone_project_voters);$i++)
			{	
				$month = date('F',strtotime($iphone_project_voters[$i]['ProjectRating']['created']));
				$year = date('Y',strtotime($iphone_project_voters[$i]['ProjectRating']['created']));
				$date = date('d',strtotime($iphone_project_voters[$i]['ProjectRating']['created']));
				$created = $month." ".$date;
				
				
				
				$image_options = array(
            			'dimension' => 'iphone_project_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				$image_url = Router::url('/', true).$this->ProjectRating->Project->getImageUrl('UserAvatar', $iphone_project_voters[$i]['User']['UserAvatar'], $image_options);
				
				$iphone_project_voter[$i]['Voters username'] = $iphone_project_voters[$i]['User']['username'];
				$iphone_project_voter[$i]['Voters user image'] = $image_url;
				$iphone_project_voter[$i]['Vote created'] = $created;
				$iphone_project_voter[$i]['Vote count'] = $iphone_project_voters[$i]['ProjectRating']['rating'];
			}
			$this->view = 'Json';
			$this->set('json',$iphone_project_voter);
		
			}
			$projectRatings = $this->paginate();
            $this->set('projectRatings', $projectRatings);
            if (!empty($this->request->params['named']['type']) and $this->request->params['named']['type'] == 'votes') {
            $this->autoRender = false;
            $this->render('votes');
        }
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function add($project_id = null, $rate = null)
    {
        if (is_null($project_id) || is_null($rate)) {
            throw new NotFoundException(__l('Invalid request'));
        }
		$rate = ($rate <= 0) ? 0 : (($rate > 5) ? 5 : $rate);
		if (empty($rate)) {
			throw new NotFoundException(__l('Invalid request'));
		}
        $project = $this->ProjectRating->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id ,
            ) ,
            'contain' => array(
                'User' => array(
                    'fields' => array(
                        'User.email',
                        'User.username'
                    )
                ) ,
                'ProjectFund' => array(
                    'User' => array(
                        'fields' => array(
                            'User.id',
                            'User.username',
                            'User.email',
                        )
                    ) ,
                    'fields' => array(
                        'ProjectFund.user_id'
                    )
                ) ,
                'ProjectRating' => array(
                    'fields' => array(
                        'ProjectRating.user_id'
                    ) ,
                    'conditions' => array(
                        'ProjectRating.user_id' => $this->Auth->user('id')
                    )
                ) ,
                'ProjectFollower' => array(
                    'fields' => array(
                        'ProjectFollower.user_id'
                    )
                )
            ) ,
            'fields' => array(
                'Project.id',
                'Project.user_id',
                'Project.name',
                'Project.slug',
                'Project.project_status_id',
            ) ,
            'recursive' => 2
        ));
        if (!empty($project)) {
			if ($project['Project']['user_id'] != $this->Auth->user('id')) {
              if (empty($project['ProjectRating'])) {
            	if($project['Project']['project_status_id'] == ConstProjectStatus::OpenForIdea)
            	{
                	$this->ProjectRating->create();
					$this->request->data['ProjectRating']['user_id'] = $this->Auth->user('id');
					$this->request->data['ProjectRating']['rating'] = $rate;
					$this->request->data['ProjectRating']['project_id'] = $project_id;
					$this->request->data['ProjectRating']['ip_id'] = $this->ProjectRating->toSaveIp();
					$this->request->data['ProjectRating']['action'] = 'add';
					if ($this->ProjectRating->save($this->request->data)) {
						$this->ProjectRating->Project->updateAll(array(
							'Project.total_ratings' => 'Project.total_ratings + ' . $rate
						) , array(
							'Project.id' => $project_id
						));
						// sending Mail to owner
						$owner_user[] = $project['Project']['user_id'];
						$return_owner_lists = $this->_sendAlertOnProjectRating(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
						// send mail to backed
						$pledged_users = Set::extract('/ProjectFund/user_id', $project);
						$pledged_user_lists = $this->_sendAlertOnProjectRating(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
						// send mail to followers
						$follow_users = Set::extract('/ProjectFollower/user_id', $project);
						$this->_sendAlertOnProjectRating(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
						$this->Session->setFlash(__l('Voting has been added') , 'default', null, 'success');
					} else {
						$this->Session->setFlash(__l('Voting could not be added. Please, try again') , 'default', null, 'error');
					}
				}
				else
				{
                   $this->Session->setFlash(__l('Invalid request.') , 'default', null, 'error');
                }
                }
                 else {
					$this->Session->setFlash(__l('You have already voted this project') , 'default', null, 'error');
				}
			} else {
				$this->Session->setFlash(__l('You cannot vote your project') , 'default', null, 'error');
			}
            if ($this->RequestHandler->isAjax()) {
                $project = $this->ProjectRating->Project->find('first', array(
                    'conditions' => array(
                        'Project.id' => $project_id
                    ) ,
                    'fields' => array(
                        'Project.id',
                        'Project.total_ratings',
                        'Project.project_rating_count',
						'Project.actual_rating',
                    ) ,
                    'recursive' => - 1
                ));
                $this->set('project', $project);
            } else {
                $this->redirect(array(
                    'controller' => 'projects',
                    'action' => 'view',
                    $project['Project']['slug']
                ));
            }
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
		$this->set('rate',$rate);
        $this->pageTitle = __l('Add Project Voting');
    }
    public function _sendAlertOnProjectRating($to_users, $project, $projectUserType, $user_lists = array())
    {
        if (!empty($to_users)) {
            $users = $this->ProjectRating->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => - 1
            ));
            // Send private messsage on project comment add
            $subject = __l('New Project Voting');
            $message = $this->Auth->User('username') . ' ' . __l('has voted the project') . ' "' . $project['Project']['name'] . '"';
            $message_id = $this->ProjectRating->Project->Message->sendNotifications($to_users, $subject, $message, $project['Project']['id']);
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->ProjectRating->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_rating_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_rating_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_rating_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Rating Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => $this->ProjectRating->changeFromEmail(($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from']) ,
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => $this->Auth->User('username') ,
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    public function admin_index()
    {
        $this->_redirectGET2Named(array(
            'q'
        ));
        $this->pageTitle = __l('Project Votings');
        $conditions = array();
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'day') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectRating.created) <= '] = 0;
            $this->pageTitle.= __l(' - Added today');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'week') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectRating.created) <= '] = 7;
            $this->pageTitle.= __l(' - Added in this week');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'month') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectRating.created) <= '] = 30;
            $this->pageTitle.= __l(' - Added in this month');
        }
        if (isset($this->request->params['named']['q'])) {
            $conditions['AND']['OR'][]['Project.name LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['User.username LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->params['named']['q']);
        }
        if (!empty($this->request->params['named']['project_id'])) {
            $conditions['project_id'] = $this->request->params['named']['project_id'];
            $project_name = $this->ProjectRating->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->params['named']['project_id'],
                ) ,
                'fields' => array(
                    'Project.name',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle.= sprintf(__l(' - Project - %s') , $project_name['Project']['name']);
        }
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'Project' => array(
                    'ProjectStatus',
                ) ,
                'User',
            ) ,
            'order' => array(
                'ProjectRating.id' => 'desc'
            )
        );
        $this->ProjectRating->recursive = 0;
        $this->set('projectRatings', $this->paginate());
        $moreActions = $this->ProjectRating->moreActions;
        $this->set(compact('moreActions'));
    }
    public function admin_update()
    {
        if (!empty($this->request->data[$this->modelClass])) {
            $r = $this->request->data[$this->modelClass]['r'];
            $actionid = $this->request->data[$this->modelClass]['more_action_id'];
            unset($this->request->data[$this->modelClass]['r']);
            unset($this->request->data[$this->modelClass]['more_action_id']);
            $selectedIds = array();
            foreach($this->request->data[$this->modelClass] as $primary_key_id => $is_checked) {
                if ($is_checked['id']) {
                    $selectedIds[] = $primary_key_id;
                }
            }
            if ($actionid && !empty($selectedIds)) {
                if ($actionid == ConstMoreAction::Delete) {
                    $this->{$this->modelClass}->deleteAll(array(
                        $this->modelClass . '.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked project votings has been deleted') , 'default', null, 'success');
                }
            }
        }
        $this->redirect(Router::url('/', true) . $r);
    }
    public function admin_delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->ProjectRating->delete($id)) {
            $this->Session->setFlash(__l('Project Voting deleted') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
}
?>